package com.open.spring.service.impl; 

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.util.CollectionUtils;

import com.open.spring.entity.SysPropertiesBean;
/**
 * 重写spring读取系统文件的方法 
 * @author lism
 *
 */
public class InitSysPropertiesService extends PropertyPlaceholderConfigurer{
	private static Logger logger = LoggerFactory.getLogger(InitSysPropertiesService.class);
	@Override
	protected void processProperties(
			ConfigurableListableBeanFactory beanFactory, Properties props)
			throws BeansException {
		
		
		Map<String,String> sysMap = SysPropertiesBean.getInstance().getSysMap();
		String sysProperties = sysMap.get("sysProperties");
		String sysPropertiesPath = sysMap.get("sysPropertiesPath");
		logger.info(sysPropertiesPath);
		logger.info(sysProperties);
		
		InputStream inst = null;
		//优先读取服务器的配置，若服务器没有配置文件则读取本工程下面的配置文件
		
		File file = new File(sysPropertiesPath);
		if(null!=file&&file.isFile()){
			try {
				inst = new FileInputStream(file);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} 
		}else{
			InputStream is = this.getClass().getClassLoader().getResourceAsStream(sysProperties);
			inst = is;
		}
		
		Properties p = new Properties();
		try {
			p.load(inst);
		} catch (IOException e) {
			e.printStackTrace();
		}
		CollectionUtils.mergePropertiesIntoMap(props, p);
		
		super.processProperties(beanFactory, p);
	}

	
}
